package com.ztgf.shopping.api.cms.shop;

import com.baomidou.mybatisplus.plugins.Page;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.vo.CommodityEvaluationScoreVO;
import com.ztgf.commodity.models.vo.CommodityInfoRankVO;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.order.models.service.IOrderInfoService;
import com.ztgf.order.models.vo.OrderInfoSalesVO;
import com.ztgf.search.models.dto.EsShopDTO;
import com.ztgf.search.models.service.IShopSearchService;
import com.ztgf.shopping.models.bo.shop.*;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.service.shop.IShopQiyuesuoInfoService;
import com.ztgf.shopping.models.vo.shop.*;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.user.models.service.IUserLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * 店铺表控制器
 *
 * @author zhanghualang
 * @Date 2020-05-28 14:35:39
 */

@RestController
@RequestMapping("/cms/shopInfo")
@Slf4j
@Api(value = "ShopInfoController", tags = "店铺表接口")
public class ShopInfoController {

    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private IOrderInfoService iOrderInfoService;
    @DubboReference
    private ICommodityInfoService iCommodityInfoService;
    @DubboReference
    private IShopQiyuesuoInfoService iShopQiyuesuoInfoService;
    @DubboReference
    private IUserLoginService iUserLoginService;
    @DubboReference
    private ISmsInfoService iSmsInfoService;
    @DubboReference
    private IShopSearchService shopSearchService;

    /**
     * 根据店铺id修改支付类型
     *
     * @param shopId
     * @param payType
     * @return
     */
    @ApiOperation(value = "更新支付类型根据店铺id", notes = "更新支付类型根据店铺id")
    @PostMapping("/updatePayTypeByShopId")
    public Result updatePayTypeByShopId(Long shopId, Integer payType) {
        boolean b = shopInfoService.updatePayTypeByShopId(shopId, payType);
        if (b) {
            return new Result();
        }
        return new Result(CodeEnum.FAIL_100008);
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据店铺ID查询店铺信息，店铺管理使用", notes = "根据店铺ID查询店铺信息，店铺管理使用")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result<ShopInfoDTO> get(@RequestParam("id") Long id) {
        ShopInfoDTO dto = shopInfoService.selectById(id);
        return new Result<>(dto);
    }

    @PostMapping("/getVO")
    @ApiOperation(value = "根据店铺ID查询店铺信息，用户管理使用", notes = "根据店铺ID查询店铺信息，用户管理使用")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result<ShopInfoVO> getVO(@RequestParam("id") Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ShopInfoVO vo = shopInfoService.selectVoById(id);
        if (vo.getId() == null) {
            return new Result<>(CodeEnum.FAIL);
        } else {
            return new Result<>(vo);
        }
    }

    @PostMapping("/updatePurchaseFeeMoneyFreeTimes")
    @ApiOperation(value = "修改砍价服务费免费次数", notes = "修改砍价服务费免费次数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopId", value = "shopId", required = true, paramType = "query", dataType = "Long")
            , @ApiImplicitParam(name = "times", value = "times", required = true, paramType = "query", dataType = "Integer")
    })
    public Result updatePurchaseFeeMoneyFreeTimes(Long shopId, Integer times) {
        if (times == null || shopId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ShopInfoDTO dto = new ShopInfoDTO();
        dto.setId(shopId);
        dto.setPurchaseFeeMoneyFreeTimes(times);
        boolean flag = shopInfoService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL);
        }
    }

    @PostMapping("/getUseStatistics")
    @ApiOperation(value = "用户统计", notes = "用户统计")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result<ShopInfoUseStatisticsVO> getUseStatistics(Long id) {
        ShopInfoUseStatisticsVO vo = shopInfoService.getUseStatistics(id);
        return new Result<>(vo);
    }

    @PostMapping("/getVariousShop")
    @ApiOperation(value = "获取各种店铺数量", notes = "获取各种店铺数量")
    public Result<HashMap<String, Integer>> getVariousShop() {
        HashMap<String, Integer> map = shopInfoService.getVariousShop();
        return new Result<>(map);
    }

    @ApiOperation(value = "店铺表列表", notes = "店铺表列表")
    @PostMapping("/queryManageList")
    public Result<Page<ShopInfoManageVO>> queryPageList(ShopInfoBO bo) {
        Page<ShopInfoManageVO> page = shopInfoService.queryPageList(bo);
        return new Result<>(page);
    }

    @ApiOperation(value = "异常店铺表列表", notes = "异常店铺表列表")
    @PostMapping("/queryAbnormalList")
    public Result<Page<ShopInfoAbnormalVO>> queryAbnormalList(ShopInfoBO bo) {
        Page<ShopInfoAbnormalVO> page = shopInfoService.queryAbnormaPageList(bo);
        return new Result<>(page);
    }

    @PostMapping("/getUser")
    @ApiOperation(value = "获取根据店铺ID获取用户信息", notes = "获取根据店铺ID获取用户信息")
    public Result<ShopInfoUserVO> getUser(Long id, Integer type) {
        Integer imType = type;
        if (type == null) {
            imType = 0;
        }
        ShopInfoUserVO vo = shopInfoService.getUser(id, imType);
        return new Result<>(vo);
    }

    @PostMapping("/getScore")
    @ApiOperation(value = "根据id获取店铺评分", notes = "根据id获取店铺评分")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result<CommodityEvaluationScoreVO> getScore(@RequestParam("id") Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        CommodityEvaluationScoreVO vo = shopInfoService.getScore(id);
        return new Result<>(vo);
    }

    @PostMapping("/getSales")
    @ApiOperation(value = "根据id获取店铺销售额", notes = "根据id获取店铺销售额")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result<List<OrderInfoSalesVO>> getSales(ShopInfoSalesBO bo) {
        if (bo.getId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        List<OrderInfoSalesVO> vos = iOrderInfoService.querySalesList(bo.getId(), DateUtils.dateToStr(bo.getStartDate(), DateUtils.DATE_FORMAT_DATEDAY), DateUtils.dateToStr(bo.getEndDate(), DateUtils.DATE_FORMAT_DATEDAY));
        return new Result<>(vos);
    }

    @PostMapping("/getVariousCommodity")
    @ApiOperation(value = "获取店铺里各种商品数量", notes = "获取店铺里各种商品数量")
    public Result<HashMap<String, Integer>> getVariousCommodity(Long id) {
        HashMap<String, Integer> map = iCommodityInfoService.getVariousCommodity(id);
        return new Result<>(map);
    }

    @PostMapping("/getCommoditySalesRank")
    @ApiOperation(value = "获取店铺商品销量排名", notes = "获取店铺商品销量排名")
    public Result<List<CommodityInfoRankVO>> getCommoditySalesRank(Long id) {
        List<CommodityInfoRankVO> vos = iCommodityInfoService.getCommoditySalesRank(id);
        return new Result<>(vos);
    }

    @PostMapping("/closeShop")
    @ApiOperation(value = "关店", notes = "关店")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
            , @ApiImplicitParam(name = "userId", value = "userId", required = true, paramType = "query", dataType = "Long")
    })
    public Result updateCloseShop(Long id, Long userId) {
        if (id == null || userId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        boolean closeFlag = shopInfoService.updateCloseShop(id, userId);
        if (closeFlag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100049);
        }
    }

    @PostMapping("/freezeShop")
    @ApiOperation(value = "admin冻结店铺", notes = "admin冻结店铺")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
            , @ApiImplicitParam(name = "userId", value = "userId", required = true, paramType = "query", dataType = "Long")
    })
    public Result freezeShop(Long id, Long userId) {
        if (id == null || userId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        boolean flag = shopInfoService.updateAdminFreeze(id, userId);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL);
        }
    }

    @PostMapping("/updateFreezeShop")
    @ApiOperation(value = "admin解冻店铺", notes = "admin解冻店铺")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
            , @ApiImplicitParam(name = "userId", value = "userId", required = true, paramType = "query", dataType = "Long")
    })
    public Result updateFreezeShop(Long id, Long userId) {
        if (id == null || userId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ShopInfoDTO dto = new ShopInfoDTO();
        dto.setId(id);
        dto.setFrozenStatus(0);//冻结状态 0未冻结，1冻结 2关店
        dto.setAdminFrozenStatus(0);//冻结状态 0未冻结，1冻结 2关店
        dto.setUpdateUserId(userId);
        boolean flag = shopInfoService.updateById(dto);
        if (flag) {
            // TODO admin解冻店铺更新店铺ES
            List<EsShopDTO> esShopDTOS = shopInfoService.queryEsShop(id.toString());
            shopSearchService.addShop("index_shop_2020", "shop", 0, esShopDTOS.size(), esShopDTOS);
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL);
        }
    }

    @PostMapping("/sealShop")
    @ApiOperation(value = "封停账号", notes = "封停账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
            , @ApiImplicitParam(name = "userId", value = "userId", required = true, paramType = "query", dataType = "Long")
    })
    public Result sealShop(Long id, Long userId) {
        if (id == null || userId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ShopInfoDTO dto = new ShopInfoDTO();
        dto.setId(id);
        dto.setBuyerStatus(1);//状态 0未冻结，1冻结
        dto.setUpdateUserId(userId);
        boolean flag = shopInfoService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL);
        }
    }

    @PostMapping("/updateSealShop")
    @ApiOperation(value = "解封封停账号（买家）", notes = "解封封停账号（买家）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
            , @ApiImplicitParam(name = "userId", value = "userId", required = true, paramType = "query", dataType = "Long")
    })
    public Result updateSealShop(Long id, Long userId) {
        if (id == null || userId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ShopInfoDTO dto = new ShopInfoDTO();
        dto.setId(id);
        dto.setBuyerStatus(0);//状态 0未冻结，1冻结
        dto.setUpdateUserId(userId);
        boolean flag = shopInfoService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL);
        }
    }


    @PostMapping("/updateShopName")
    @ApiOperation(value = "更改店铺名称", notes = "更改店铺名称")
    public Result updateShopName(ShopInfoUpdateNameBO bo) {
        if (bo.getId() == null || bo.getCreateUserId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById(bo.getId());
        ShopInfoDTO dto = new ShopInfoDTO();
        dto.setId(bo.getId());
        if (shopInfoDTO.getType().equals(0)) {
            dto.setShopName(bo.getShopName() + "专营店");
        } else if (shopInfoDTO.getType().equals(1)) {
            dto.setShopName(bo.getShopName() + "专卖店");
        } else if (shopInfoDTO.getType().equals(2)) {
            dto.setShopName(bo.getShopName() + "旗舰店");
        } else if (shopInfoDTO.getType().equals(3)) {
            dto.setShopName(bo.getShopName() + "自营店");
        }

        dto.setUpdateUserId(bo.getCreateUserId());
        boolean flag = shopInfoService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL);
        }
    }

    @ApiOperation(value = "所有用户列表，用户管理使用", notes = "所有用户列表，用户管理使用")
    @PostMapping("/queryAllList")
    public Result<Page<ShopInfoAllVO>> queryAllList(ShopInfoAllBO bo) {
        Page<ShopInfoAllVO> page = shopInfoService.queryAllList(bo);
        return new Result<>(page);
    }

    @ApiOperation(value = "赊销订单预期次数", notes = "赊销订单预期次数")
    @PostMapping("/queryOverdueList")
    public Result<Page<ShopOverdueVO>> queryOverdueList(ShopOverdueBO bo) {
        Page<ShopOverdueVO> page = shopInfoService.queryOverdueList(bo);
        return new Result<>(page);
    }

//    @ApiOperation(value = "根据类型获取所有名称，店铺名，店铺id，手机号，邮箱，发送消息使用",notes = "根据类型获取所有店铺id，手机号，邮箱，发送消息使用")
//    @PostMapping("/queryInfoByType")
//    @ApiImplicitParam(name = "type",value = "0全部用户，1全部店铺，2全部旗舰店，3全部专卖店，4全部专营店，5全部买家",required = true,paramType = "query", dataType = "Integer")
//    public Result<ShopInfoTypeVO> queryInfoByType(Integer type){
//        //type 0全部用户，1全部店铺，2全部旗舰店，3全部专卖店，4全部专营店，5全部买家
//        ShopInfoTypeVO vo = shopInfoService.queryInfoByType(type);
//        return new Result<>(vo);
//    }

    @ApiOperation(value = "查询店铺，发送消息使用", notes = "查询店铺，发送消息使用")
    @PostMapping("/queryList")
    public Result<List<ShopInfoVO>> queryList(ShopInfoQueryBO bo) {
        if (bo.getMerchantType().equals(0)) {
            //若是买家，则可以查出所有店铺
            bo.setMerchantType(null);
        }
        List<ShopInfoVO> vos = shopInfoService.queryList(bo);
        return new Result<>(vos);
    }

    @ApiOperation(value = "根据店铺ID获取电子签章是否已有", notes = "根据店铺ID获取电子签章是否已有")
    @PostMapping("/getQiyuesuoByShopId")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result queryInfoByType(@RequestParam("id") Long id) {
        return new Result<>(iShopQiyuesuoInfoService.getPassStatusByShopId(id));
    }

    @ApiOperation(value = "查询店铺，代客下单使用", notes = "查询店铺，代客下单使用")
    @PostMapping("/getDKInfo")
    public Result<ShopInfoVO> getDKInfo(ShopInfoDKBO bo) {
        ShopInfoVO vo = shopInfoService.getDKInfo(bo);
        return new Result<>(vo);
    }

    @ApiOperation(value = "查询店铺，发送消息使用(分页)", notes = "查询店铺，发送消息使用（分页）")
    @PostMapping("/queryPageList")
    public Result<Page<ShopInfoVO>> queryPageList (ShopInfoQueryBO bo) {
        Page<ShopInfoVO> vos = shopInfoService.queryPageListBySms (bo);
        return new Result<>(vos);
    }

    @ApiOperation(value = "设置用户平台砍价服务费(固定费率)", notes = "设置用户平台砍价服务费（固定费率）")
    @PostMapping("/setPurchaseFeeMoney")
    public Result<?> setPurchaseFeeMoney (ShopInfoUpdateBO bo) {
        if(bo == null || bo.getId () == null || bo.getPurchaseFeeMoney () ==null ){
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ShopInfoDTO shopInfoDTO = new ShopInfoDTO ();
        shopInfoDTO.setId (bo.getId ());
        shopInfoDTO.setPurchaseFeeMoney (bo.getPurchaseFeeMoney ());
        boolean updateById = shopInfoService.updateById (shopInfoDTO);
        if (updateById){
            return new Result<>(CodeEnum.SUCCESS);
        }else {
            return new Result<>(CodeEnum.FAIL);
        }
    }

    @ApiOperation(value = "设置用户平台砍价服务费率（买家）", notes = "设置用户平台砍价服务费（买家）")
    @PostMapping("/setPurchaseFeeMoneyScale")
    public Result<?> setPurchaseFeeMoneyScale (ShopInfoUpdateBO bo) {
        if(bo == null || bo.getId () == null || bo.getPurchaseFeeMoneyScale () ==null ||
                bo.getPurchaseFeeMoneyScale ().compareTo (new BigDecimal (100)) == 1){
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ShopInfoDTO shopInfoDTO = new ShopInfoDTO ();
        shopInfoDTO.setId (bo.getId ());
        shopInfoDTO.setPurchaseFeeMoneyScale (bo.getPurchaseFeeMoneyScale ().divide (new BigDecimal (100)));
        boolean updateById = shopInfoService.updateById (shopInfoDTO);
        if (updateById){
            return new Result<>(CodeEnum.SUCCESS);
        }else {
            return new Result<>(CodeEnum.FAIL);
        }
    }

    @ApiOperation(value = "设置用户平台砍价服务费（卖家）", notes = "设置用户平台砍价服务费（卖家）")
    @PostMapping("/setPurchaseDividendScale")
    public Result<?> setPurchaseDividendScale (ShopInfoUpdateBO bo) {
        if(bo == null || bo.getId () == null || bo.getPurchaseDividendScale () ==null ||
                bo.getPurchaseDividendScale ().compareTo (new BigDecimal (100)) == 1){
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ShopInfoDTO shopInfoDTO = new ShopInfoDTO ();
        shopInfoDTO.setId (bo.getId ());
        shopInfoDTO.setPurchaseDividendScale (bo.getPurchaseDividendScale ().divide (new BigDecimal (100)));
        boolean updateById = shopInfoService.updateById (shopInfoDTO);
        if (updateById){
            return new Result<>(CodeEnum.SUCCESS);
        }else {
            return new Result<>(CodeEnum.FAIL);
        }
    }

}
